import html2canvas from "html2canvas";

export const downloadTextFile = (
  content,
  filename = new Date().getTime(),
  fileSuffix
) => {
  // 字符内容转变成blob地址
  const blob = new Blob([content]);
  downloadByA(URL.createObjectURL(blob), filename, fileSuffix);
};

export const downloadByA = (
  url,
  filename = new Date().getTime(),
  fileSuffix
) => {
  const ele = document.createElement("a"); // 创建下载链接
  ele.download = `${filename}.${fileSuffix}`; //设置下载的名称
  ele.style.display = "none"; // 隐藏的可下载链接
  // 字符内容转变成blob地址
  ele.href = url;
  // 绑定点击时间
  document.body.appendChild(ele);
  ele.click();
  // 然后移除
  document.body.removeChild(ele);
};

export const canvasCut = (html, isDownload = true, callback) => {
  if (!html) {
    if (callback) callback();
    return;
  }

  return html2canvas(html, {
    backgroundColor: null,
    allowTaint: true,
    useCORS: true,
  }).then((canvas) => {
    if (isDownload) {
      downloadByA(canvas.toDataURL(), undefined, "png");
    } else {
      return canvas.toDataURL();
    }
    if (callback) callback();
  });
};

export function getAssetsFile(url, ext = "png") {
  return new URL(`../assets/images/edit/${url}.${ext}`, import.meta.url).href;
}
